package ge.telasi.tasks.ui.user;

import ge.telasi.tasks.model.User;
import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.comp.ImagePanel;
import javax.swing.ImageIcon;

/**
 * @author dimitri
 */
public class UserImagePanel extends ImagePanel {
    private static final long serialVersionUID = -6572345697406708673L;

    private User user;

    public UserImagePanel() {
        super();
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
        reset();
    }

    private void reset() {
        if (user == null || user.getBinaryId() == null) {
            displayDefault();
        } else {
            try {
                long id = user.getBinaryId();
                Platform pl = Platform.getDefault();
                byte[] data = pl.getFacade().download(pl.getCredentials(), id);
                ImageIcon icon = new ImageIcon(data);
                display(icon);
            } catch (Exception ex) {
                displayDefault();
                ex.printStackTrace();
            }
        }
        setChangeable(user != null && user.equals(Platform.getDefault().getUser()));
    }

    @Override
    protected void save(byte[] data) {
        try {
            Platform pl = Platform.getDefault();
            long id = pl.getFacade().uploadUserImage(pl.getCredentials(), data);
            pl.getUser().setBinaryId(id);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }

}
